<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import type { ElMessage, ElMessageBox } from 'element-plus'
import EditForm from '@/views/system/sysdict/Edit.vue'
import {
  sysdictPage,
  sysdictBatchDelete,
  sysdictRemoveById,
  updateEnableByCode,
  getSysDictListTree
} from '@/apis/sysdict.js'

const instance = getCurrentInstance()
let searchEntity = reactive({
  name: '',
  code: '',
  value: '',
  parentCode: '',
  enable: null
})
let searchForm = ref()
let searchFormItem = ref()
let more = reactive({ state: false, icon: 'ArrowDown', text: '展开' })
let tableData = reactive({
  current: 1,
  size: 10,
  total: 0,
  pages: 0,
  records: []
})

let selected = ref([])

let editfrom = ref()

function selectionChange(selection) {
  selected.value = selection
}

function handleSizeChange(size) {
  tableData.size = size
  getPage()
}

function handleCurrentChange(current) {
  tableData.current = current
  getPage()
}

function resetForm() {
  if (!searchForm) return
  searchForm.value.resetFields()
}

function showMore() {
  if (more.state) {
    searchFormItem.value.style.height = '52px'
    more.state = false
    more.text = '展开'
    more.icon = 'ArrowDown'
  } else {
    searchFormItem.value.style.height = '100%'
    more.state = true
    more.icon = 'ArrowUp'
    more.text = '收起'
  }
  instance.ctx.$forceUpdate()
}

function handleEdit(code, method) {
  editfrom.value.open(code, method)
}

function getPage() {
  sysdictPage({
    current: tableData.current,
    size: tableData.size,
    name: searchEntity.name,
    code: searchEntity.code,
    value: searchEntity.value,
    parentCode: searchEntity.parentCode,
    enable: searchEntity.enable
  })
    .then((res) => {
      tableData.current = res.current
      tableData.size = res.size
      tableData.total = res.total
      tableData.pages = res.pages
      tableData.records = res.records
    })
    .catch((error) => {
      console.log(error)
    })

  getListTree()
}

function getIndex(index) {
  return (tableData.current - 1) * tableData.size + index + 1
}

function batchDelete() {
  ElMessageBox.confirm('确定要删除 ' + selected.value.length + ' 条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      sysdictBatchDelete(selected.value.map((elem) => elem.code))
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

function handleDelete(code) {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      sysdictRemoveById(code)
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '删除成功'
            })
            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

function updateEnable(row, code, enable) {
  row.enable = !enable
  ElMessageBox.confirm('确定要修改当前状态吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      updateEnableByCode(code, enable)
        .then(function (response) {
          if (response) {
            ElMessage({
              type: 'success',
              message: '修改成功'
            })

            getPage()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消修改'
      })

      getPage()
    })
}

let treeList = reactive({
  tree: {
    list: []
  }
})

function getListTree() {
  treeList.tree.list = []
  getSysDictListTree()
    .then((response) => {
      response.forEach((element) => {
        let obj = {
          value: element.id,
          label: element.name,
          children: []
        }
        if (
          element.children != null &&
          element.children != undefined &&
          element.children.length > 0
        ) {
          element.children.forEach((children) => {
            obj.children.push({
              value: children.id,
              label: children.name
            })
          })
        }
        treeList.tree.list.push(obj)
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

onMounted(() => {
  getPage()
})
</script>

<template>
  <el-card class="searchForm" header="查询条件" shadow="never">
    <template #header>
      <div class="card-header">
        <el-icon style="color: rgb(12 43 77)" size="18"><Operation /></el-icon>
        <h1>查询条件</h1>
      </div>
    </template>
    <el-form inline :model="searchEntity" label-width="70px" ref="searchForm">
      <div ref="searchFormItem" style="height: 52px; overflow: hidden">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="searchEntity.name" placeholder="字典名称"> </el-input>
        </el-form-item>

        <el-form-item label="字典键" prop="code">
          <el-input v-model="searchEntity.code" placeholder="字典键"> </el-input>
        </el-form-item>

        <el-form-item label="字典值" prop="value">
          <el-input v-model="searchEntity.value" placeholder="字典值"> </el-input>
        </el-form-item>

        <el-form-item label="上级字典" prop="parentCode">
          <el-tree-select
            v-model="searchEntity.parentCode"
            :data="treeList.tree.list"
            check-strictly
            :render-after-expand="false"
            placeholder="上级字典"
            style="width: 180px"
          ></el-tree-select>
        </el-form-item>

        <el-form-item label="状态" prop="enable">
          <el-select-v2
            v-model="searchEntity.enable"
            :options="[
              { value: 1, label: '启用' },
              { value: 0, label: '停用' }
            ]"
            placeholder="状态"
          />
        </el-form-item>
      </div>

      <el-row style="justify-content: center">
        <el-button type="primary" auto-insert-space icon="Search" @click="getPage">搜索</el-button>
        <el-button auto-insert-space icon="CircleClose" @click="resetForm">重置</el-button>
        <el-button type="primary" link @click="showMore"
          >{{ more.text
          }}<el-icon class="el-icon--right"><component :is="more.icon"></component></el-icon
        ></el-button>
      </el-row>
    </el-form>
  </el-card>

  <div class="dataTable">
    <el-row class="tableBtn">
      <!-- <el-button-group class="ml-4"> -->
      <el-button
        type="primary"
        icon="CirclePlus"
        auto-insert-space
        @click="handleEdit(null, 'add')"
        v-has="'sysdict:add'"
        >新增</el-button
      >

      <el-button
        type="danger"
        icon="Delete"
        auto-insert-space
        :disabled="!selected.length"
        @click="batchDelete"
        v-has="'sysdict:del'"
        >删除</el-button
      >
      <el-text type="warning" style="margin-left: 2em"
        >温馨提醒：该功能请在开发人员的指引下使用，请勿随意修改参数数据，以免造成系统无法使用！</el-text
      >

      <!-- <el-button type="warning" icon="Download" auto-insert-space>导出</el-button> -->
      <!-- </el-button-group> -->
    </el-row>
    <el-row>
      <el-table
        :data="tableData.records"
        border
        stripe
        max-height="550"
        size="small"
        fit
        @selection-change="selectionChange"
        :header-cell-style="tableHeaderStyle"
        show-overflow-tooltip
      >
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center">
          <template #default="scope">
            <span v-text="getIndex(scope.$index)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="字典名称" width="150"></el-table-column>
        <el-table-column prop="code" label="字典键" width="150"></el-table-column>
        <el-table-column prop="value" label="字典值" width="200"></el-table-column>
        <el-table-column prop="parentName" label="上级字典" width="150"></el-table-column>
        <el-table-column
          prop="sort"
          label="排序"
          width="80"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column prop="enable" label="状态" width="75" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              inline-prompt
              active-text="启用"
              inactive-text="停用"
              @click="updateEnable(scope.row, scope.row.code, scope.row.enable)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column
          prop="createTime"
          label="添加时间"
          width="130"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column align="center" width="180" v-has="['sysdict:edit', 'sysdict:del']"  fixed="right">
          <template #header>操作</template>
          <template #default="scope">
            <el-button
              size="small"
              icon="Edit"
              type="primary"
              @click="handleEdit(scope.row.code, 'edit')"
              v-has="'sysdict:edit'"
              >编辑</el-button
            >
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              @click="handleDelete(scope.row.code)"
              v-has="'sysdict:del'"
            >
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="dataTablePage">
      <el-pagination
        background
        :current-page="tableData.current"
        :page-size="tableData.size"
        :default-page-size="10"
        :page-sizes="[10, 20, 30, 40]"
        layout="sizes, prev, pager, next, jumper, ->, total"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-row>
  </div>

  <edit-form ref="editfrom" @getPage="getPage"></edit-form>
</template>
<style scoped lang="scss"></style>
